//
//  JSPhotoBrowsViewController.m
//  JSPhotoPicker
//
//  Created by JasonLee on 2018/8/14.
//  Copyright © 2018年 JasonLee. All rights reserved.
//

#import "JSPhotoBrowsViewController.h"
#import "JSImageBrowsCell.h"
#import "UIImage+JSUtility.h"
#import "JSPhotoPickerCommon.h"
static CGFloat TOOL_BAR_HEIGHT = 44;
static NSInteger PHOTO_DEFAULT_SHOW_MAX_COUNT = 9;
@interface JSPhotoBrowsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong)UICollectionView *collectionView;

// 标记View
@property (strong,nonatomic)    UIToolbar *toolBar;
@property (weak,nonatomic)      UILabel *makeView;
@property (strong,nonatomic)    UIButton *doneBtn;
@property (nonatomic,strong) UIButton *selectButton;
@end

@implementation JSPhotoBrowsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.collectionView];
    [self setupToorBar];
    [self updateMakeViewStatus:self.selectedAssetArray.count];
    [self updateDoneBtnStatus:self.selectedAssetArray.count];
    self.title = [NSString stringWithFormat:@"%ld/%lu",(long)self.currentIndex + 1,(unsigned long)self.assetArray.count];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.selectButton];
}

#pragma mark     UICollectionViewDataSource

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    JSImageBrowsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JSImageBrowsCell" forIndexPath:indexPath];
    if (indexPath.row < self.assetArray.count) {
        [cell updateCellWithImage:self.assetArray[indexPath.row]];
    }
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.assetArray.count;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
#pragma mark     UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake([UIScreen mainScreen].bounds.size.width + 10, [UIScreen mainScreen].bounds.size.height - 44-[UIApplication sharedApplication].statusBarFrame.size.height - TOOL_BAR_HEIGHT - ([[UIScreen mainScreen] bounds].size.height == 812 ? 34:0));
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
    self.currentIndex = index;
    self.title = [NSString stringWithFormat:@"%ld/%lu",(long)self.currentIndex + 1,(unsigned long)self.assetArray.count];
    self.selectButton.selected = [self.selectedAssetArray containsObject:self.assetArray[self.currentIndex]];
}
-(void)done{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:PICKER_TAKE_DONE object:nil userInfo:@{@"selectAssets":self.selectedAssetArray}];
    });
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)selectAction:(UIButton *)selectButton{
    NSInteger maxCount = (self.maxCount <= 0) ? PHOTO_DEFAULT_SHOW_MAX_COUNT :self.maxCount;
    selectButton.selected = !selectButton.selected;
    if (selectButton.selected && ![self.selectedAssetArray containsObject:self.assetArray[self.currentIndex]]) {
        if (self.selectedAssetArray.count < maxCount) {
            [self.selectedAssetArray addObject:self.assetArray[self.currentIndex]];
        }else{
            selectButton.selected = !selectButton.selected;
            NSString *alertStr = [NSString stringWithFormat:@"最多只能选择%ld张图片",(long)maxCount];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:alertStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"好的", nil];
            [alertView show];
            return ;
        }
        
    }else{
        [self.selectedAssetArray removeObject:self.assetArray[self.currentIndex]];
    }
    self.doneBtn.enabled = self.selectedAssetArray.count != 0;
    [self updateMakeViewStatus:self.selectedAssetArray.count];
}
-(void)updateMakeViewStatus:(NSInteger)count{
    self.makeView.text = [NSString stringWithFormat:@"%lu",count];
    self.makeView.hidden = !count;
}
-(void)updateDoneBtnStatus:(NSInteger)count{
    self.doneBtn.enabled = count;
}
-(UIImage *)screenShotImageFrom:(UIView *)view{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.frame = CGRectMake(0, 44+[UIApplication sharedApplication].statusBarFrame.size.height, [UIScreen mainScreen].bounds.size.width + 10, [UIScreen mainScreen].bounds.size.height - 44 - [UIApplication sharedApplication].statusBarFrame.size.height - TOOL_BAR_HEIGHT - ([[UIScreen mainScreen] bounds].size.height == 812 ? 34:0));
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[JSImageBrowsCell class] forCellWithReuseIdentifier:@"JSImageBrowsCell"];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.pagingEnabled = YES;
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentIndex inSection:0] atScrollPosition:(UICollectionViewScrollPositionNone) animated:YES];
        _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
         if (@available(iOS 11.0, *)) {
             _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
         }
    }
    return _collectionView;
}
- (void) setupToorBar{
    UIToolbar *toorBar = [[UIToolbar alloc] init];
    toorBar.barTintColor = [UIColor whiteColor];
    toorBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:toorBar];
    self.toolBar = toorBar;
    
    NSDictionary *views = NSDictionaryOfVariableBindings(toorBar);
    NSString *widthVfl =  @"H:|-0-[toorBar]-0-|";
    NSString *heightVfl = @"V:[toorBar(44)]-0-|";
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:widthVfl options:0 metrics:0 views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:heightVfl options:0 metrics:0 views:views]];
    
    // 左视图 中间距 右视图
    UIBarButtonItem *fiexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.doneBtn];
    self.doneBtn.enabled = NO;
    toorBar.items = @[fiexItem,rightItem];
}
- (UIButton *)doneBtn{
    if (!_doneBtn) {
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setTitleColor:[UIColor colorWithRed:0/255.0 green:91/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
        rightBtn.enabled = YES;
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        rightBtn.frame = CGRectMake(0, 0, 45, 45);
        [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
        [rightBtn addSubview:self.makeView];
        self.doneBtn = rightBtn;
    }
    return _doneBtn;
}
#pragma mark makeView 红点标记View
- (UILabel *)makeView{
    if (!_makeView) {
        UILabel *makeView = [[UILabel alloc] init];
        makeView.textColor = [UIColor whiteColor];
        makeView.textAlignment = NSTextAlignmentCenter;
        makeView.font = [UIFont systemFontOfSize:13];
        makeView.frame = CGRectMake(25, -5, 20, 20);
        makeView.hidden = YES;
        makeView.layer.cornerRadius = makeView.frame.size.height / 2.0;
        makeView.clipsToBounds = YES;
        makeView.backgroundColor = [UIColor redColor];
        [self.view addSubview:makeView];
        self.makeView = makeView;
        
    }
    return _makeView;
}
#pragma mark deleleBtn
- (UIButton *)selectButton{
    if (!_selectButton) {
        _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_selectButton setImage:[UIImage imageNamed:JSPhotoPickerSrcName(@"icon_image_no")] forState:UIControlStateNormal];
        [_selectButton setImage:[UIImage imageNamed:JSPhotoPickerSrcName(@"icon_image_yes")] forState:UIControlStateSelected];
        _selectButton.frame = CGRectMake(0, 0, 35, 35);
        [_selectButton addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
        _selectButton.selected = [self.selectedAssetArray containsObject:self.assetArray[self.currentIndex]];
        
    }
    return _selectButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
